/**
 * 路由拦截
 * Created by mlr on 2016/9/6.
 */
var express = require('express')
    ,   path    = require('path')
    ,   router  = express.Router()
    ,   useragent = require('express-useragent')
    ,   Rload   = require(path.join(APP_BASE.R, 'load.js'))
    ,   config = require('config')
    ,   webConfig = require('config').get('web');

var _router = function(app){
    router.use(useragent.express());
    router.all('*\.do|*\.out', function(req, res, next){
        var Action;
        if (req.path.indexOf('upload') != -1) {
            Action = Rload.Fload(req.path);
        } else {
            Action = Rload.Aload(req.path);
        }
        if(Action && typeof Action == 'function') {
            Action.call(app, req, res, next);
        } else {
            res.status(404).send({err: 1, errMsg: '文件' + req.path+ ' 未找到!'});
        }
    });

    router.all('*preview*|*edit*', function(req, res, next) {
        var reqPath = req.path;
        var Action = Rload.Aload(reqPath);
        if(Action && typeof Action == 'function') {
            Action.call(app, req, res, next);
        } else {
            res.status(404).send({err: 1, errMsg: '文件' + reqPath + ' 未找到!'});
        }
    });

    // 网站页面路由 其内部做PC与移动的区分路由
    router.use(function(req, res, next) {
        var reqPath = req.path;
        var flag_download = reqPath.indexOf('download') != -1;
        if (flag_download) {
            var fileName = reqPath.replace('/download/','');
            reqPath = "/download.do";
            req.query.name = fileName;
            Action = Rload.Fload(reqPath);
            if(Action && typeof Action == 'function') {
                Action.call(app, req, res, next);
            } else {
                res.status(404).send({err: 1, errMsg: '文件' + fileName+ ' 未找到!'});
            }
        } else {
            reqPath && (reqPath = reqPath.substring(1));
            res.render('index', {title: webConfig.title, moduleName: reqPath || 'doc/list'});
        }
    });

    // catch 404 and forward to error handler
    router.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    return router;
};
module.exports = _router;
